package com.jiazhong.basic.pack0718;

import java.lang.reflect.Field;

// 反射---属性
public class DemoC {

    public static void main(String[] args) throws Exception {
        Class c = Class.forName("com.jiazhong.pack0718.Student");
        // 获取到该类的定义的所有属性
        Field[] declaredFields = c.getDeclaredFields();
        // 获取到该类的拥有的所有非私有属性
        Field[] fields = c.getFields();
        for (Field field : declaredFields) {
            System.out.println(field);
        }
        System.out.println("---------------------------------------------");
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("---------------------------------------------");
        // 获取到该类的定义的某个属性
        // Field declaredField1 = c.getDeclaredField("name"); // ❌
        Field declaredField2 = c.getDeclaredField("address");
        // 获取到该类拥有的某个属性
        Field field3 = c.getField("name");
        // System.out.println(declaredField1);
        System.out.println(declaredField2);
        System.out.println(field3);
        // 操作属性
        Object obj = c.getDeclaredConstructor().newInstance();
        // 可见
        declaredField2.setAccessible(true);
        declaredField2.set(obj, "陕西西安");
        declaredField2.setAccessible(true);
        Object val = declaredField2.get(obj);
        System.out.println(val);
    }
}
